package com.rose.datax.dataxadmin.manager.impl;

import com.rose.datax.dataxadmin.manager.JobFileGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class RedisMessageSubscriber implements MessageListener {

    @Resource
    private JobFileGenerator jobFileGenerator;

    @Resource
    private TransferTask transferTask;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String taskId = message.toString();
        log.info("Message received: " + taskId);
        String channel = new String(message.getChannel());
        switch (channel){
            case "task-run":
                long task_id = Long.parseLong(taskId);
                executeMigrationTask(task_id);
                break;
        }
    }

    private void executeMigrationTask(long taskId){
        if(jobFileGenerator.execute(taskId)) {
            transferTask.transfer(taskId);
        }
    }

}
